# 发送钉钉信息

import requests

from zz import zz_code, zz_log, zz_return, zz_str

log = zz_log.of()


def get_api_url():
    return zz_code.env("DINGTALK_TOKEN")


def get_secret():
    return zz_code.env("DINGTALK_SECRET")


# 发markdown消息
def send_markdown(msg, title, at_all=False) -> zz_return.Return:
    post_data = {
        "msgtype": "markdown",
        "markdown": {
            "title": title,
            "text": msg,
        },
        "at": {
            "isAtAll": at_all
        }
    }
    return send_api(post_data)


# 调用接口
def send_api(post_data) -> zz_return.Return:
    if zz_str.is_null_or_empty(get_api_url()):
        return zz_return.of(20036, "dingtalk miss api_url")
    timestamp = zz_code.date_timestamp_ms()
    timestamp = str(timestamp)
    sign_str = sign(timestamp)
    query = zz_str.map_to_query({
        'timestamp': timestamp,
        'sign': sign_str,
    })

    api_url = f"{get_api_url()}&{query}"
    r = zz_return.of(123456)
    log.debug(api_url)
    log.debug(post_data)
    try:
        res = requests.post(api_url, json=post_data)
        r = zz_return.parse(res.content)
    except Exception as ex:
        log.error(ex)
        r = zz_return.of(123456, ex)
    log.debug(r.to_json())

    return r


# 签名
def sign(timestamp):
    string1 = f"{timestamp}\n{get_secret()}"
    sign = zz_str.hmacSHA256(string1, get_secret())
    log.debug(f"string1: {string1}")
    log.debug(f"sign: {sign}")

    return sign
